<template>
  <div class="draw-manage">
    <div class="page-header">
      <h2>抽奖列表管理</h2>
      <p>管理抽奖活动和中奖记录</p>
    </div>

    <div class="search-bar">
      <el-form :model="searchForm" inline>
        <el-form-item label="活动名称">
          <el-input v-model="searchForm.activityName" placeholder="请输入活动名称" clearable />
        </el-form-item>
        <el-form-item label="参与用户">
          <el-input v-model="searchForm.userName" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="中奖状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="已中奖" value="已中奖" />
            <el-option label="未中奖" value="未中奖" />
          </el-select>
        </el-form-item>
        <el-form-item label="抽奖时间">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        <el-icon>
          <Plus />
        </el-icon>
        创建抽奖活动
      </el-button>
      <el-button @click="refreshData">
        <el-icon>
          <Refresh />
        </el-icon>
        刷新
      </el-button>
      <el-button type="success" @click="exportData">
        <el-icon>
          <Download />
        </el-icon>
        导出数据
      </el-button>
    </div>

    <el-table :data="tableData" v-loading="loading" stripe>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="activityName" label="活动名称" width="150" />
      <el-table-column prop="userName" label="参与用户" width="120" />
      <el-table-column prop="userPhone" label="用户手机" width="130" />
      <el-table-column prop="prizeName" label="奖品名称" width="150">
        <template #default="{ row }">
          <span v-if="row.prizeName" style="color: #67c23a; font-weight: bold;">
            {{ row.prizeName }}
          </span>
          <span v-else style="color: #909399;">未中奖</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="中奖状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === '已中奖' ? 'success' : 'info'">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="drawTime" label="抽奖时间" width="180" />
      <el-table-column prop="deliveryStatus" label="发放状态" width="100">
        <template #default="{ row }">
          <el-tag v-if="row.status === '已中奖'" :type="row.deliveryStatus === '已发放' ? 'success' : 'warning'">
            {{ row.deliveryStatus }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
          <el-button v-if="row.status === '已中奖' && row.deliveryStatus === '待发放'" type="success" size="small"
            @click="handleDeliver(row)">
            发放奖品
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
        :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 创建抽奖活动对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="resetForm">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="formData.activityName" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入活动描述" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="formData.startTime" type="datetime" placeholder="选择开始时间" format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="formData.endTime" type="datetime" placeholder="选择结束时间" format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="参与条件" prop="condition">
          <el-input v-model="formData.condition" placeholder="请输入参与条件" />
        </el-form-item>
        <el-form-item label="活动状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="进行中">进行中</el-radio>
            <el-radio label="已结束">已结束</el-radio>
            <el-radio label="未开始">未开始</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailVisible" title="抽奖详情" width="500px">
      <div v-if="currentDetail" class="detail-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="活动名称">{{ currentDetail.activityName }}</el-descriptions-item>
          <el-descriptions-item label="参与用户">{{ currentDetail.userName }}</el-descriptions-item>
          <el-descriptions-item label="用户手机">{{ currentDetail.userPhone }}</el-descriptions-item>
          <el-descriptions-item label="抽奖时间">{{ currentDetail.drawTime }}</el-descriptions-item>
          <el-descriptions-item label="中奖状态">
            <el-tag :type="currentDetail.status === '已中奖' ? 'success' : 'info'">
              {{ currentDetail.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentDetail.prizeName" label="中奖奖品">
            {{ currentDetail.prizeName }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentDetail.status === '已中奖'" label="发放状态">
            <el-tag :type="currentDetail.deliveryStatus === '已发放' ? 'success' : 'warning'">
              {{ currentDetail.deliveryStatus }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentDetail.remark" label="备注">
            {{ currentDetail.remark }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  activityName: '',
  userName: '',
  status: '',
  dateRange: []
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const formRef = ref<FormInstance>()
const detailVisible = ref(false)
const currentDetail = ref<any>(null)

// 表单数据
const formData = reactive({
  activityName: '',
  description: '',
  startTime: '',
  endTime: '',
  condition: '',
  status: '未开始'
})

// 表单验证规则
const rules = {
  activityName: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    { min: 2, max: 50, message: '活动名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  condition: [
    { required: true, message: '请输入参与条件', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择活动状态', trigger: 'change' }
  ]
}

// 模拟数据
const mockData = [
  {
    id: 1,
    activityName: '新年抽奖活动',
    userName: '张三',
    userPhone: '138****1234',
    prizeName: 'iPhone 15 Pro',
    status: '已中奖',
    drawTime: '2024-01-15 14:30:25',
    deliveryStatus: '已发放',
    remark: '已通过快递发送'
  },
  {
    id: 2,
    activityName: '新年抽奖活动',
    userName: '李四',
    userPhone: '139****5678',
    prizeName: '',
    status: '未中奖',
    drawTime: '2024-01-15 14:28:15',
    deliveryStatus: '',
    remark: ''
  },
  {
    id: 3,
    activityName: '春节特惠抽奖',
    userName: '王五',
    userPhone: '156****9012',
    prizeName: '100元优惠券',
    status: '已中奖',
    drawTime: '2024-01-14 16:45:30',
    deliveryStatus: '待发放',
    remark: ''
  },
  {
    id: 4,
    activityName: '春节特惠抽奖',
    userName: '赵六',
    userPhone: '187****3456',
    prizeName: '',
    status: '未中奖',
    drawTime: '2024-01-14 15:20:10',
    deliveryStatus: '',
    remark: ''
  },
  {
    id: 5,
    activityName: '新年抽奖活动',
    userName: '孙七',
    userPhone: '176****7890',
    prizeName: '现金红包',
    status: '已中奖',
    drawTime: '2024-01-13 10:15:45',
    deliveryStatus: '已发放',
    remark: '已发放到微信账户'
  }
]

// 获取数据
const fetchData = () => {
  loading.value = true

  // 模拟API请求
  setTimeout(() => {
    let filteredData = [...mockData]

    // 应用搜索条件
    if (searchForm.activityName) {
      filteredData = filteredData.filter(item =>
        item.activityName.toLowerCase().includes(searchForm.activityName.toLowerCase())
      )
    }
    if (searchForm.userName) {
      filteredData = filteredData.filter(item =>
        item.userName.toLowerCase().includes(searchForm.userName.toLowerCase())
      )
    }
    if (searchForm.status) {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }

    tableData.value = filteredData
    total.value = filteredData.length
    loading.value = false
  }, 500)
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.activityName = ''
  searchForm.userName = ''
  searchForm.status = ''
  searchForm.dateRange = []
  handleSearch()
}

// 刷新数据
const refreshData = () => {
  fetchData()
  ElMessage.success('数据已刷新')
}

// 导出数据
const exportData = () => {
  ElMessage.success('导出功能开发中')
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  fetchData()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchData()
}

// 创建活动
const handleAdd = () => {
  dialogTitle.value = '创建抽奖活动'
  resetForm()
  dialogVisible.value = true
}

// 查看详情
const handleView = (row: any) => {
  currentDetail.value = row
  detailVisible.value = true
}

// 发放奖品
const handleDeliver = (row: any) => {
  ElMessageBox.confirm(
    `确定要发放奖品"${row.prizeName}"给用户"${row.userName}"吗？`,
    '发放确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟发放操作
    ElMessage.success('奖品发放成功')
    fetchData()
  }).catch(() => {
    // 取消发放
  })
}

// 删除记录
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除用户"${row.userName}"的抽奖记录吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟删除操作
    ElMessage.success('删除成功')
    fetchData()
  }).catch(() => {
    // 取消删除
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    // 模拟API请求
    setTimeout(() => {
      submitLoading.value = false
      dialogVisible.value = false
      ElMessage.success('创建成功')
      fetchData()
    }, 1000)

  } catch (error) {
    console.log('表单验证失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  formData.activityName = ''
  formData.description = ''
  formData.startTime = ''
  formData.endTime = ''
  formData.condition = ''
  formData.status = '未开始'

  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.draw-manage {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 20px;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-bar {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.detail-content {
  padding: 10px 0;
}
</style>
